#include "ObjectRef.h"



_NS_OOP_BEGIN



ObjectRef::ObjectRef () :
__p_obj (NULL)
{

}



ObjectRef::~ObjectRef ()
{
	setNull ();
}



ObjectRef::ObjectRef (const ObjectRef& r_right) :
__p_obj (r_right.__p_obj)
{
	__incrRef ();
}



ObjectRef::ObjectRef (ObjectRef&& rr_right) :
__p_obj (rr_right.__p_obj)
{
	rr_right.__p_obj = NULL;
}



ObjectRef&
ObjectRef::operator= (const ObjectRef& r_right)
{
	setNull ();
	__p_obj = r_right.__p_obj;
	__incrRef ();
	return *this;
}



ObjectRef&
ObjectRef::operator= (ObjectRef&& rr_right)
{
	setNull ();
	__p_obj = rr_right.__p_obj;
	rr_right.__p_obj = NULL;
	return *this;
}



void
ObjectRef::setNull ()
{
	__decrRef ();
	__tryRelease ();
	__p_obj = NULL;
}



bool
OOP::ObjectRef::operator== (const ObjectRef& r_ref) const
{
	return __p_obj == r_ref.__p_obj;
}



bool
OOP::ObjectRef::operator== (void* ptr) const
{
	return __p_obj == ptr;
}



bool
OOP::ObjectRef::operator!= (const ObjectRef& r_ref) const
{
	return __p_obj != r_ref.__p_obj;
}



bool
OOP::ObjectRef::operator!= (void* ptr) const
{
	return __p_obj != ptr;
}



ObjectRef::ObjectRef (Object* p_obj) :
__p_obj (p_obj)
{
	__incrRef ();
}



void
ObjectRef::__incrRef ()
{
	if (__p_obj)
		__p_obj->_incrRef ();
}



void
ObjectRef::__decrRef ()
{
	if (__p_obj)
		__p_obj->_decrRef ();
}



int
ObjectRef::__getRef () const
{
	if (!__p_obj)
		return 0;
	return __p_obj->_refNum;
}



bool
ObjectRef::__shouldRelease () const
{
	return __p_obj && __p_obj->_refNum <= 0;
}



void
ObjectRef::__tryRelease ()
{
	if (__shouldRelease ())
		__release ();
}



void
ObjectRef::__release ()
{
	delete __p_obj;
	__p_obj = NULL;
}



_NS_OOP_END